package com.coisini.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.coisini.constant.MessageConstant;
import com.coisini.context.BaseContext;

import com.coisini.dto.*;
import com.coisini.entity.*;
import com.coisini.exception.AddressBookBusinessException;

import com.coisini.exception.OrderBusinessException;
import com.coisini.exception.ShoppingCartBusinessException;
import com.coisini.mapper.*;
import com.coisini.result.PageResult;
import com.coisini.service.OrderService;
import com.coisini.utils.WeChatPayUtil;
import com.coisini.vo.OrderPaymentVO;
import com.coisini.vo.OrderStatisticsVO;
import com.coisini.vo.OrderSubmitVO;

import com.coisini.vo.OrderVO;
import com.coisini.webSocket.WebSocketServer;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.Size;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;


@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 1.提交订单
     *
     * 1.处理异常（购物车为空异常，地址簿为空异常）
     * 2.操作订单表，向其添加一条数据
     * 3.操作订单明细表，向其添加n条数据
     * 4.根据用户id清空其购物车
     * 4.构建OrderSubmitVO对象，并返回
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //1.处理异常
        //根据ordersSubmitDTO里面的地址簿id查询地址
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //根据用户id获取购物车信息
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = ShoppingCart.builder().userId(userId).build();
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.size() == 0){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //构建订单对象
        Orders orders=new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setUserId(userId);
        orders.setStatus(Orders.PENDING_PAYMENT); //订单状态：待付款
        orders.setPayStatus(Orders.UN_PAID); //支付状态 ： 未支付
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));//订单号设置为当前时间的时间戳
        orders.setAddress(addressBook.getDetail());
        orders.setDeliveryStatus(Orders.IMMEDIATE_DELIVERY);  // 配送状态 立即配送

        //2.操作订单表，向其添加一条数据
       orderMapper.insert(orders);

        //订单明细数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        //3.操作订单明细表，向其添加n条数据 批量插入
        orderDetailMapper.insertBatch(orderDetailList);


        //4.清空购物车
        shoppingCartMapper.delete(shoppingCart);


        //5.构建OrderSubmitVO对象，并返回
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .build();
        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.00), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );


        JSONObject jsonObject = new JSONObject();
        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }


        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);


        Map map=new HashMap();
        map.put("type",1); //来单提醒
        map.put("orderId", orders.getId()); // 订单id
        map.put("content", "订单号：" + outTradeNo); //订单号
        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 历史订单分页查询
     * 1.需要查询订单表，
     * 2.同时还需要查询订单明细表
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult pageQuery(Integer page, Integer pageSize, Integer status) {
       //1.设置查询条件
        PageHelper.startPage(page,pageSize);

        //2.调用mapper接口进行查询
        OrdersPageQueryDTO ordersPageQueryDTO=new OrdersPageQueryDTO();
        ordersPageQueryDTO.setPage(page);
        ordersPageQueryDTO.setPageSize(pageSize);
        ordersPageQueryDTO.setStatus(status);
        List<Orders> ordersList = orderMapper.page(ordersPageQueryDTO);
        Page<Orders> ordersPage= (Page<Orders>) ordersList;

        //3.遍历ordersList集合，利用订单id查询每个订单关联的订单明细
        //定义一个集合，用来存储每个订单的所有信息
        List<OrderVO> list=new ArrayList<>();
        for (Orders orders : ordersList) {
            Long ordersId = orders.getId();
            //根据订单id在订单明细表中查询
            List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(ordersId);

            //将每一个订单及其订单对应的明细添加到存储集合中
            OrderVO orderVO=new OrderVO();
            BeanUtils.copyProperties(orders,orderVO);
            orderVO.setOrderDetailList(orderDetailList);
            list.add(orderVO);
        }

        //4.返回查询结果
        //这里的返回数据第二个参数，应当是所有订单的详细信息,直接将list集合返回即可
        return new PageResult(ordersPage.getTotal(),list);
    }

    /**
     * 根据订单id查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO getById(Long id) {
        Orders orders = orderMapper.getById(id);
        OrderVO orderVO=new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(orderDetailMapper.getByOrderId(orderVO.getId()));
        return orderVO;
    }

    /**
     * 再来一单
     * 1.根据当前订单id获取order_detail表中的信息
     * 2.将其重新添加到购物车中
     * @param id
     */
    @Override
    @Transactional
    public void repetition(Long id) {
        //获取当前的用户的id
        Long userId = BaseContext.getCurrentId();
        //根据当前的订单id获取订单明细
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        //对orderDetailList集合进行数据转换
        /*List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(new Function<OrderDetail, ShoppingCart>() {
            @Override
            public ShoppingCart apply(OrderDetail orderDetail) {
                ShoppingCart shoppingCart = new ShoppingCart();
                BeanUtils.copyProperties(orderDetail, shoppingCart);
                shoppingCart.setUserId(userId);
                shoppingCart.setCreateTime(LocalDateTime.now());
                return shoppingCart;
            }
        }).collect(Collectors.toList());*/
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(orderDetail ->{
                ShoppingCart shoppingCart = new ShoppingCart();
                BeanUtils.copyProperties(orderDetail, shoppingCart);
                shoppingCart.setUserId(userId);
                shoppingCart.setCreateTime(LocalDateTime.now());
                return shoppingCart;
            }
        ).collect(Collectors.toList());

        //将数据批量插入shopping_cart表中
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    /**
     * 取消订单
     * 待支付和待接单状态下，用户可直接取消订单
     * 商家已接单状态下，用户取消订单需电话沟通商家
     * 派送中状态下，用户取消订单需电话沟通商家
     * 如果在待接单状态下取消订单，需要给用户退款
     * 取消订单后需要将订单状态修改为“已取消”
     * @param id
     */
    @Override
    public void cancel(Long id) throws Exception {
        //先根据id获取订单
        Orders orders = orderMapper.getById(id);

        //对订单进行判断
        //1.订单不存在
        if (orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //2.对订单的状态进行判断
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        /*if (orders.getStatus() > 2){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }*/

        Orders newOrders = new Orders();
        newOrders.setId(orders.getId());

        //3.订单处于待接单状态下取消，需要进行退款
        if (orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //调用微信支付退款接口
            weChatPayUtil.refund(
                    orders.getNumber(), //商户订单号
                    orders.getNumber(), //商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01));//原订单金额

            //支付状态修改为 退款
            newOrders.setPayStatus(Orders.REFUND);
        }

        // 更新订单状态、取消原因、取消时间
        newOrders.setStatus(Orders.CANCELLED);
        newOrders.setCancelReason("用户取消");
        newOrders.setCancelTime(LocalDateTime.now());
        orderMapper.update(newOrders);
    }

    /**
     * 管理端订单搜索，分页查询
     * 输入订单号/手机号进行搜索，支持模糊搜索
     * 根据订单状态进行筛选
     * 下单时间进行时间筛选
     * 搜索内容为空，提示未找到相关订单
     * 搜索结果页，展示包含搜索关键词的内容
     * 分页展示搜索到的订单数据
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        //1.设置查询条件
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());

        //2.调用mapper接口进行查询
        List<Orders> ordersList = orderMapper.page(ordersPageQueryDTO);
        Page<Orders> ordersPage= (Page<Orders>) ordersList;

        // 部分订单状态，需要额外返回订单菜品信息，将Orders转化为OrderVO
        List<OrderVO> orderVOList = getOrderVOList(ordersPage);

        return new PageResult(ordersPage.getTotal(),orderVOList);
    }

    /**
     * 该方法将Orders类型的集合转换成OrderVO类型的集合
     * @param page
     * @return
     */
    private List<OrderVO> getOrderVOList(Page<Orders> page){
        List<OrderVO> orderVOList=new ArrayList<>();

        List<Orders> ordersList = page.getResult();
        //对集合进行判断，可以同时判空和长度，不会报空指针异常
        if (!CollectionUtils.isEmpty(ordersList)) {
            for (Orders orders : ordersList) {
                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                //获取菜品信息
                String orderDishes = getOrderDishesStr(orders);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }
        return orderVOList;

    }

    /**
     *  根据订单id获取菜品信息字符串
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }

    /**
     * 获取各个状态订单的数量
     * 将状态常量传递过去，在数据库中使用聚合函数进行统计
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        // 根据状态，分别查询出待接单、待派送、派送中的订单数量
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);

        // 将查询出的数据封装到orderStatisticsVO中响应
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    /**
     * 商家接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED) //修改为已结单状态
                .build();

        orderMapper.update(orders);
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 校验订单是否存在，并且状态为3
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     * 验证订单是否存在，并且状态为配送中
     * @param id
     */
    @Override
    public void complete(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 校验订单是否存在，并且状态为4
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
    }

    /**
     * 拒单
     * 1.查询orders表，获取当前id的订单信息
     * 2.只有当订单状态为待接单时可以拒绝
     * 3.拒单之后还需要退款
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
       // 1.查询orders表，获取当前id的订单信息
        Orders ordersDB = orderMapper.getById(ordersRejectionDTO.getId());

        // 订单只有存在且状态为2（待接单）才可以拒单
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //2.退款
       /* Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == Orders.PAID) {
            //用户已支付，需要退款
            String refund = weChatPayUtil.refund(
                    ordersDB.getNumber(),
                    ordersDB.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            log.info("申请退款：{}", refund);
        }*/

        //更新当前订单信息
        Orders orders = Orders.builder()
                .id(ordersRejectionDTO.getId())
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .status(Orders.CANCELLED)
                .cancelTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
    }

    /**
     * 用户催单
     * 1.根据订单id查询订单，判断订单是否存在
     * 2.利用webSocket进行双向交流
     * @param id
     */
    public void reminder(Long id) {
        // 查询订单是否存在
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //基于WebSocket实现催单
        Map map = new HashMap();
        map.put("type", 2);//2代表用户催单
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());
        //向服务端发送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
}
